window.spdevlab = window.spdevlab || {};
window.spdevlab.jsappwebpart = window.spdevlab.jsappwebpart || {};

(function (app) {

    app.ApplicationPicker = function () { };

    app.ApplicationPicker.prototype.init = function (options, resultContextId) {

        app._options = options;

        var appSelectorModel = function () {

            var selApp = this;

            selApp.selectedApp = null;

            selApp.apps = ko.observableArray([]);

            selApp.onSelectApp = function (data) {
                selApp.selectedApp = data;

                ko.utils.arrayForEach(selApp.apps(), function (app) {
                    app.isSelected(0);
                });

                selApp.selectedApp.isSelected(1);
            };

            selApp.onSelectAppCancel = function (data) {
                SP.UI.ModalDialog.commonModalDialogClose();
            };

            selApp.onSelectAppSave = function () {

                if (selApp.selectedApp != null) {
                    app._toolpartModelInstance.appTitle(selApp.selectedApp.title);
                    app._toolpartModelInstance.appUrl(selApp.selectedApp.url);

                    app._toolpartModelInstance.updateAppJsonSettings();
                }

                SP.UI.ModalDialog.commonModalDialogClose();
            };

            selApp.activeApps = ko.computed(function () {

                return ko.utils.arrayFilter(selApp.apps(), function (app) {
                    return app.isVisible() == 1;
                });
            });

            selApp.searchAppsStringValue = "";
            selApp.searchAppsString = ko.computed({

                read: function () {
                    return selApp.searchAppsStringValue;
                },

                write: function (value) {
                    selApp.searchAppsStringValue = value;
                    selApp.searchApps(selApp.searchAppsStringValue);
                }
            });

            selApp.searchApps = function (value) {

                if (value == "") {
                    ko.utils.arrayForEach(selApp.apps(), function (app) {
                        app.isVisible(1);
                    });
                }
                else {
                    ko.utils.arrayForEach(selApp.apps(), function (app) {

                        if (app.title.toLowerCase().indexOf(value.toLowerCase()) >= 0) {
                            app.isVisible(1);
                        }
                        else {
                            app.isVisible(0);
                        }
                    });
                }
            };

            selApp.loadApps = function (appSelectorContainer) {

                var clientContext = new SP.ClientContext(app._options.rootWebUrl);
                var appList = clientContext.get_web().get_lists().getByTitle('Master Page Gallery');
                var camlQuery = new SP.CamlQuery();

                camlQuery.set_viewXml("<View Scope='Folder'>" +
                					  	"<Query> " +
                					  		"<Where>" +
                					  			"<Eq>" +
                					  				"<FieldRef Name='FSObjType' />" +
                					  				"<Value Type='Lookup'>1</Value>" +
                					  			"</Eq>" +
                					  		"</Where>" +
                					  	"</Query>" +
                					  	"</View>");

                var appFolderPath = "/JsAppWebPart/apps";

                if (app._options.rootWebUrl != "/")
                    appFolderPath = app._options.rootWebUrl + appFolderPath;

                camlQuery.set_folderServerRelativeUrl(appFolderPath);

                var appItems = appList.getItems(camlQuery);

                clientContext.load(appItems, "Include(EncodedAbsUrl,FileRef,FileLeafRef,Title, Id)");

                clientContext.executeQueryAsync(function () {

                    selApp.apps.removeAll();

                    var appItemEnumerator = appItems.getEnumerator();

                    while (appItemEnumerator.moveNext()) {

                        (function (appItem) {
                            var appFolder = appItem.get_item('FileRef');
                            var appMetaContainerClass = "app-item-" + appItem.get_id().toString();

                            var itemId = appItem.get_id();

                            var appModel = {
                                title: appItem.get_item('FileLeafRef'),
                                isSelected: ko.observable(app._options.selectedAppFolderPath == appFolder ? 1 : 0),
                                isVisible: ko.observable(1),
                                url: appFolder,
                                id: itemId,
                                itemClass: appMetaContainerClass,
                                metaDescription: ko.observable(""),
                                metaImgUrl: ko.observable("")
                            };

                            selApp.apps.push(appModel);

                            var appAbsFolder = appItem.get_item('EncodedAbsUrl');

                            var metaUrl = appAbsFolder + '/app.meta.htm';
                            var metaImageUrl = appAbsFolder + '/app.meta.png';

                            jQuery.get(metaUrl, function (data) {
                                appModel.metaDescription(data);
                            });

                            appModel.metaImgUrl(metaImageUrl);
                        })(appItemEnumerator.get_current());
                    }

                }, function (sender, args) {
                    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
                });
            };
        };

        var toolpartModel = function () {

            var tpModel = this;

            tpModel.updateAppJsonSettings = function () {

                var resultContextContainer = document.getElementById(resultContextId);

                resultContextContainer.value = ko.toJSON({
                    selectedAppFolderPath: tpModel.appUrl(),
                    selectedAppTitle: tpModel.appTitle()
                });
            };

            tpModel.showJsAppSettings = function () {

                var appSelectorContainer = document
	   								.getElementById(app._options.containerId + "-app-selector")
	   								.cloneNode(true);

                ExecuteOrDelayUntilScriptLoaded(function () {

                    SP.UI.ModalDialog.showModalDialog({
                        html: appSelectorContainer,
                        title: 'Js App Repository',
                        autoSize: true,
                        width: 690,
                        height: 500,
                        allowMaximize: false
                    });

                    appSelectorContainer.style.display = "";
                    var appSelectorModelInstance = new appSelectorModel();

                    appSelectorModelInstance.loadApps();

                    ko.applyBindings(appSelectorModelInstance, appSelectorContainer);
                }, "sp.js");
            };

            tpModel.appTitle = ko.observable(app._options.selectedAppTitle);
            tpModel.appUrl = ko.observable(app._options.selectedAppFolderPath);
        };

        app._toolpartModelInstance = new toolpartModel();

        ko.applyBindings(app._toolpartModelInstance, document.getElementById(app._options.containerId + "-tool-selector"));
    };

})(window.spdevlab.jsappwebpart);

SP.SOD.notifyScriptLoadedAndExecuteWaitingJobs("spdevlab.jsappwebpart.toolpart.js");